function hfile = mtc_SmoothIterativeNN(hfile, srf, nweight, numiter)
% MTC::SmoothIterativeNN  - iteratively smooth MTC (nearest neighbor)
%
% FORMAT:       [mtc] = mtc.SmoothIterativeNN(srf, nweight, numiter);
%
% Input fields:
%
%       srf         matching surface file (number of vertices)
%       nweight     neighbor weighting (divided by num. of neighbors)
%       numiter     number of iterations

% Version:  v0.7b
% Build:    7090213
% Date:     Sep-02 2007, 1:02 PM CEST
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 4 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'mtc') || ...
    numel(srf) ~= 1 || ...
   ~isBVQXfile(srf, 'srf') || ...
    numel(nweight) ~= 1 || ...
   ~isa(nweight, 'double') || ...
    isinf(nweight) || ...
    isnan(nweight) || ...
    nweight <= 0 || ...
    numel(numiter) ~= 1 || ...
   ~isa(numiter, 'double') || ...
    isinf(numiter) || ...
    isnan(numiter) || ...
    numiter ~= fix(numiter)
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end
bc = bvqxfile_getcont(hfile.L);
srfc = bvqxfile_getcont(srf.L);
if bc.NrOfVertices ~= srfc.NrOfVertices
    error( ...
        'BVQXfile:InvalidObject', ...
        'NrOfVertices mismatch between MTC and SRF.' ...
    );
end

% get neighbors
nei = srfc.Neighbors;
nv = size(nei, 1);
normw = nweight + 1;

% get initial MTC data (resolve transio if needed!)
mtcd = double(bc.MTCData(:, :));

% iterate
for ic = 1:numiter
    
    % copy data
    mtcdo = mtcd;
    
    % iterate over vertices
    for vc = 1:nv
        
        % calculus
        mtcd(:, vc) = (mtcdo(:, vc) + ...
            (nweight / nei{vc, 1}) * sum(mtcdo(:, nei{vc, 2}), 2)) / normw;
    end
end

% store result in MTC
bc.MTCData = single(mtcd);
bvqxfile_setcont(hfile.L, bc);
